﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace ApiPrototype.Formatters
{
    public class JsonNetFormatter : MediaTypeFormatter
    {
        public JsonNetFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        }

        protected override void OnWriteToStream(Type type, object value, System.IO.Stream stream, HttpContentHeaders contentHeaders, System.Net.TransportContext context)
        {
            var serializer = new JsonSerializer();
            serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            serializer.Converters.Add(new IsoDateTimeConverter());

            using (var sw = new System.IO.StreamWriter(stream))
            using (var writer = new JsonTextWriter(sw))
            {
                serializer.Serialize(writer, value);
            }
        }

        protected override object OnReadFromStream(Type type, System.IO.Stream stream, HttpContentHeaders contentHeaders)
        {
            var serializer = new JsonSerializer();
            using (var sr = new System.IO.StreamReader(stream))
            using (var reader = new JsonTextReader(sr))
            {
                var result = serializer.Deserialize(reader, type);
                return result;
            }
        }
    }
}